/*
 * To change this license header, choose License Headers in Project Properties. To change this
 * template file, choose Tools | Templates and open the template in the editor.
 */
package chalmers.game.subterranean;

import chalmers.game.subterranean.model.ISubterranean;
import chalmers.game.subterranean.model.Subterranean;
import chalmers.game.subterranean.ui.SceneFactory;
import chalmers.game.subterranean.ui.control.KeyPressedHandler;
import chalmers.game.subterranean.ui.control.KeyReleasedHandler;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import static javafx.scene.input.KeyEvent.KEY_PRESSED;
import static javafx.scene.input.KeyEvent.KEY_RELEASED;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

/**
 * 
 * @author TH
 */
public class Factory {

  private static Factory instance;
  private static ISubterranean sub;

  private final Stage mainStage;
  private static Scene startScene;
  private static Scene gameScene;

  public static Factory getInstance(Stage stage) {
    if (instance == null) {
      instance = new Factory(stage);
    }
    return instance;
  }

  private Factory(Stage stage) {
        mainStage = stage;

        stage.setOnCloseRequest((WindowEvent event) -> {
            if (event.getEventType().equals(WindowEvent.WINDOW_CLOSE_REQUEST)) {
                System.exit(0);
            }
        });

        stage.setTitle("subterranean");
    }

  public void initApp() {
    mainStage.setScene(startScene);
    mainStage.show();
  }

  private void startGame() {
    sub.start();
    mainStage.setScene(Factory.gameScene);
  }


  public void MakeModel() {
    sub = new Subterranean();
  }

  public void MakeUI() {
    mainStage.setResizable(false);
    Factory.startScene = SceneFactory.makeStartScene();
    EventHandler<KeyEvent> eventHandlerStart = new ButtonCheckerStart();
    Factory.startScene.addEventFilter(KEY_PRESSED, eventHandlerStart);

    Factory.gameScene = SceneFactory.makeGameScene();
    /**
     * These two handlers create some problem because they directly call methods in player
     */
    EventHandler<KeyEvent> keyPressedHandler = new KeyPressedHandler(sub.getPlayer());
    EventHandler<KeyEvent> keyReleasedHandler = new KeyReleasedHandler(sub.getPlayer());

    Factory.gameScene.addEventFilter(KEY_PRESSED, keyPressedHandler);
    Factory.gameScene.addEventFilter(KEY_RELEASED, keyReleasedHandler);

  }

  public class ButtonCheckerStart implements EventHandler<KeyEvent> {

    @Override
    public void handle(KeyEvent t) {
      switch (t.getCode()) {
        case SPACE:
          startGame();
          break;
      }
    }

  }

}
